package com.gitee.l0km.jsonvisitor.utils;

import static com.gitee.l0km.jsonvisitor.parser.JSONParser.ruleNames;

import com.google.common.base.Charsets;
import com.gitee.l0km.jsonvisitor.parser.JSONLexer;

/**
 * 全局共用方法<br>
 * @author guyadong
 *
 */
public class InterpreterUtils{
	private InterpreterUtils(){
		
	}
	/** 脱掉字符串前后引号 */
	public static String unquote(String input) {
		if(null != input && input.length() > 1) {
			/** 脱掉前后引号 */
			byte[] s = input.getBytes(Charsets.UTF_8);
			return new String(s,1,s.length-2,Charsets.UTF_8).replaceAll("\\\\(.)", "$1");
		}
		return input;
	}
	public static String quote(String input) {
		if(null != input) {
			return "\""+input.replace("\"", "\\\"") + "\"";
		}
		return input;
	}
	public static String literalNameOf(int tokenType){
		String name = JSONLexer.VOCABULARY.getLiteralName(tokenType);
		if(null != name&& name.length() >1) {
			return new String(name.getBytes(Charsets.UTF_8),1,name.length()-2);
		}
		return null;
	}
	/**
	 * 返回规则索引(如{@link com.gitee.l0km.jsonvisitor.parser.JSONParser#RULE_playnode}  )对应的规则名<br>
	 * 索引无效返回{@code null}
	 * @param ruleIndex
	 */
	public static String ruleNameOf(int ruleIndex) {
		try {
			return ruleNames[ruleIndex];
		} catch (IndexOutOfBoundsException e) {
			return null;
		}
	}
}
